import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求中的blogId，通过检验是否为空就可以知道是访问哪一个网页
        String blogId = req.getParameter("blogId");
        resp.setContentType("application/json; charset=utf8");
        BlogDao blogDao = new BlogDao();
        if(blogId == null) {
            //2.博客列表页
            List<Blog> blogList = blogDao.selectAll();
            resp.getWriter().write(objectMapper.writeValueAsString(blogList));
        } else {
            //2.博客详情页
            Blog blog = blogDao.selectOne(Integer.valueOf(blogId));
            resp.getWriter().write(objectMapper.writeValueAsString(blog));
        }
    }
    //发布博客
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求格式
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html; charset=utf8");
        //1.从session会话中拿到userId
        HttpSession session = req.getSession(false);
        if(session == null) {
            resp.setStatus(403);
            resp.getWriter().write("当前未登录，不可以发布博客！");
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.setStatus(403);
            resp.getWriter().write("当前未登录，不可以发布博客！");
            return;
        }
        int userId = user.getUserId();
        //2.构造blog对象，接收req请求
        Blog blog = new Blog();
        blog.setTitle(req.getParameter("title"));
        blog.setContent(req.getParameter("content"));
        blog.setUserId(userId);
        //3.将数据保存到数据库中
        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);
        //4.重定向到博客列表页
        resp.sendRedirect("blog_list.html");
    }
}









